package com.example.system.convert;

import cn.hutool.core.util.ObjectUtil;
import com.example.system.constant.AuthoritiesEnum;
import com.example.system.dto.AuthorityDto;
import com.example.system.entity.Authority;
import com.example.system.entity.RouteMeta;
import com.example.system.vo.AuthorityVo;
import com.example.system.vo.Menu;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;

/**
 * @author 王令
 * @since 2022/8/17 19:41
 */
@Mapper
public interface AuthorityConvert {

    AuthorityConvert INSTANCE = Mappers.getMapper(AuthorityConvert.class);

    static Menu toMenu(Authority authority) {
        if (authority == null) {
            return null;
        }

        Menu menu = new Menu();
        menu.setId(authority.getId());
        menu.setParentId(ObjectUtil.defaultIfNull(authority.getParentId(), 0).longValue());
        menu.setName(authority.getName());
        menu.setPath(authority.getPath());
        menu.setOrder(authority.getOrder());
        menu.setComponent(authority.getComponent());
        menu.setRedirect(authority.getRedirect());
        RouteMeta meta = authority.getMeta();
        if (meta != null) {
            meta.setTitle(authority.getTitle());
            meta.setOrder(authority.getOrder());
            menu.setMeta(meta);
        }
        return menu;
    }

    default Authority toAuthority(AuthorityDto authorityDto) {
        if (authorityDto == null) {
            return null;
        }
        Authority authority = new Authority();
        authority.setId(authorityDto.getId());
        authority.setTitle(authorityDto.getTitle());
        authority.setName(authorityDto.getName());
        authority.setType(authorityDto.getType());
        authority.setOrder(authorityDto.getOrder());
        authority.setParentId(authorityDto.getParentId());

        if (AuthoritiesEnum.isMenu(authorityDto.getType())) {
            authority.setPath(authorityDto.getPath());
            authority.setComponent(authorityDto.getComponent());
            authority.setRedirect(authorityDto.getRedirect());
            RouteMeta meta = new RouteMeta();
            meta.setCache(authorityDto.getCache());
            meta.setTitle(authorityDto.getTitle());
            meta.setOrder(authorityDto.getOrder());
            meta.setAffix(authorityDto.getAffix());
            meta.setHidden(authorityDto.getHidden());
            meta.setIcon(authorityDto.getIcon());
            authority.setMeta(meta);
        }
        return authority;
    }

    @Mapping(target = "children", ignore = true)
    AuthorityVo toAuthorityVo(Authority authority);
}
